#include "serialportThread.h"
#include "mainwindow.h"

SerialportThread* SerialportThread::Instance=0;

SerialportThread* SerialportThread::getInstance()
{
    if(Instance==0)
        Instance =new SerialportThread();
    return Instance;
}

SerialportThread::SerialportThread(QObject *parent): QObject(parent)
{
    this->moveToThread(&thread);
    thread.start();
}

void SerialportThread::run()
{
    QSqlDatabase db = dbHelper::openConnection();
    QSqlQuery query(db);

    QString insertSql= "Select SerialPort,BaudRate From ConnectionInfo;";
    query.exec(insertSql);

    QString serialNamePort;
    QString baud="0";
    while(query.next()){
        serialNamePort=query.value("SerialPort").toString();
        baud=query.value("BaudRate").toString();
    }

    serialPort = new QSerialPort(this);
    serialPort->close();

    QSerialPort::BaudRate baudRate;

    if(baud=="115200"){
        baudRate = QSerialPort::Baud115200;
    }
    else if(baud=="4800")
    {
        baudRate = QSerialPort::Baud4800;
    }
    else if(baud=="9600")
    {
        baudRate = QSerialPort::Baud9600;
    }
    else
    {
        return;
    }

    serialPort->setDataBits(QSerialPort::Data8);
    serialPort->setParity(QSerialPort::NoParity);
    serialPort->setStopBits(QSerialPort::OneStop);
    serialPort->setFlowControl(QSerialPort::NoFlowControl);
    serialPort->setPortName(serialNamePort);
    serialPort->setBaudRate(baudRate);
    if(serialPort->open(QIODevice::ReadWrite))
    {
        MainWindow::serialStatus.set(1);//连接成功
    }else{
        MainWindow::serialStatus.set(0);//连接失败
    }
    connect(serialPort,SIGNAL(readyRead()),this,SLOT(serialPortRead_Slot()));// 串口读取
}

// 接收消息
void SerialportThread::serialPortRead_Slot()
{
    QByteArray arr = serialPort->readAll();
    QString str;
    for(int c :arr)
    {
        if(c>=0)
        {
            str += QString(" %1").arg(c, 2, 16, QChar('0')).toUpper();
        }
        else
        {
            str += QString(" %1").arg(c+256, 2, 16, QChar('0')).toUpper();
        }
    }
    str= str.simplified();
    logClient->WriteLog("CommLog","接收:\n"+str);
    QStringList list=str.split(" ");

    if(list.length()>12){

        if(list[2]=="00" && list[3]=="38"){
            if(list[10]=="00" && list[11]=="00"){
                experimentStatus="00";
            }
            else if(list[10]=="00" &&list[11]=="01"){
                experimentStatus="01";
            }
        }
        if(list[7]=="07" && list[3]=="3D"){
            if(list.length()>150)//荧光数据
            {
                for(int i=12;i<list.length()-4;i+=10){
                    if(i+4>list.length()||i+5>list.length()||i+6>list.length()||i+7>list.length()||
                            i+8>list.length()||i+9>list.length()){
                        break;
                    }else {
                        QSqlDatabase db = dbHelper::openConnection();
                        QSqlQuery query(db);

                        QString sql=QString("Insert into FluorescenceData values('','%1','%2','%3',"
                                            "'%4','%5','%6','','','','')").arg(
                                    common->SixteenToTen(list[i]+" "+list[i+1]),
                                common->SixteenToTen(list[9]),
                                common->SixteenToTen(list[i+2]+" "+ list[i+3]),
                                common->SixteenToTen(list[i+4]+" "+ list[i+5]),
                                common->SixteenToTen(list[i+6]+" "+ list[i+7]),
                                common->SixteenToTen(list[i+8]+" "+ list[i+9])
                                );
                        query.exec(sql);
                    }
                }


                    QSqlDatabase db = dbHelper::openConnection();
                    QSqlQuery query(db);
                    db.transaction();
                    QString sql=QString("update FluorescenceData set SampleId=(select id from sampleInfo s "
                                        "where "
                                        "case "
                                        "when FluorescenceData.PositionNumber %1 = 0 "
                                        "then s.RowNum=7 and s.ColNum=FluorescenceData.PositionNumber/8-1 "
                                        "else "
                                        "s.RowNum = FluorescenceData.PositionNumber %1-1 and s.ColNum = FluorescenceData.PositionNumber/8 "
                                        "end)").arg("%8");
                    query.exec(sql);

                    sql="DELETE FROM FluorescenceData WHERE rowid NOT IN (SELECT MIN(rowid) FROM FluorescenceData GROUP BY positionNumber, CyclesNumber)";
                    query.exec(sql);
                    db.commit();

            }
        }

        if((list[2]=="00" && list[3]=="3A")||!tempString.isEmpty())
        {
            if(list.length()==30 )//温度数据
            {
                MainWindow::experimentStep.set(common->SixteenToTen(list[10]).toInt());
                MainWindow::experimentCircle.set(common->SixteenToTen(list[11]).toInt());

                MainWindow::tempDataOne = list[12]+" "+list[13];

                QString tempTwo=common->SixteenToTen(list[14]+" "+list[15]);
                MainWindow::tempDataTwo=tempTwo.toDouble()/100;

                QString tempThree=common->SixteenToTen(list[16]+" "+list[17]);
                MainWindow::tempDataThree=tempThree.toDouble()/100;

                QString tempFour=common->SixteenToTen(list[18]+" "+list[19]);
                MainWindow::tempDataFour=tempFour.toDouble()/100;

                QString tempFive=common->SixteenToTen(list[20]+" "+list[21]);
                MainWindow::tempDataFive=tempFive.toDouble()/100;

                QString tempSix=common->SixteenToTen(list[22]+" "+list[23]);
                MainWindow::tempDataSix=tempSix.toDouble()/100;

                MainWindow::tempOrder = list[25].toInt();
                MainWindow::canRefChart.set(1);
            }
            if(list.length()>400)//荧光数据
            {
                if(list[list.length()-2]!="AA"&& list[list.length()-1]!="55"){
                    tempString.append(str);
                }
                else
                {
                    tempString.append(" "+str);
                    str=tempString;
                    tempString.clear();
                    QStringList list1=str.split(" ");
                    for(int i=12;i<list1.length()-4;i+=10){
                        if(i+4>list1.length()||i+5>list1.length()||i+6>list1.length()||i+7>list1.length()||
                                i+8>list1.length()||i+9>list1.length()){
                            break;
                        }else{
                            QSqlDatabase db = dbHelper::openConnection();
                            QSqlQuery query(db);

                            QString sql=QString("Insert into FluorescenceData values('','%1','%2','%3',"
                                                "'%4','%5','%6','','','','')").arg(
                                        common->SixteenToTen(list1[i]+" "+list1[i+1]),
                                    common->SixteenToTen(list1[11]),
                                    common->SixteenToTen(list1[i+2]+" "+ list1[i+3]),
                                    common->SixteenToTen(list1[i+4]+" "+ list1[i+5]),
                                    common->SixteenToTen(list1[i+6]+" "+ list1[i+7]),
                                    common->SixteenToTen(list1[i+8]+" "+ list1[i+9])
                                    );
                            query.exec(sql);
                        }
                    }
                    QSqlDatabase db = dbHelper::openConnection();
                    QSqlQuery query(db);

                    db.transaction();
                    QString sql=QString("update FluorescenceData set SampleId=(select id from sampleInfo s "
                                        "where "
                                        "case "
                                        "when FluorescenceData.PositionNumber %1 = 0 "
                                        "then s.RowNum=7 and s.ColNum=FluorescenceData.PositionNumber/8-1 "
                                        "else "
                                        "s.RowNum = FluorescenceData.PositionNumber %1-1 and s.ColNum = FluorescenceData.PositionNumber/8 "
                                        "end)").arg("%8");
                    query.exec(sql);

                    sql="DELETE FROM FluorescenceData WHERE rowid NOT IN (SELECT MIN(rowid) FROM FluorescenceData GROUP BY positionNumber, CyclesNumber)";
                    query.exec(sql);
                    db.commit();
                    MainWindow::canRefChart.set(0);
                }
            }
        }

    }
}

void SerialportThread::serialPortSend(QByteArray data){
    serialPort->write(data);
}

void SerialportThread::serialclose(){
    if(serialPort->isOpen())
    {
        serialPort->close();
    }
}
